<template
  ><!---->
  <div id="kyDetail" class="sceneDetail">
    <div style="margin-bottom: 20px;" class="sceneStep">
      <div class="step-group" style="width:100%;">
        <Steps :current="step">
          <Step
            title="科研筹划"
            @click.native="changeStep(0)"
          ></Step>
          <Step
            title="科研执行"
            @click.native="changeStep(1)"
          ></Step>
          <Step
            title="科研结项"
            @click.native="changeStep(2)"
          ></Step>
        </Steps>
        <!-- <p
          style="color:#f00;"
          v-if="projectInfo.status == 3 && drillDetail.progress == 4 && needTip"
        >
          【您的环境将于<Time
            :time="destoryTime"
            type="datetime"
          />时自动回收，若仍需保留，请在回收前重新开始配置比赛】
        </p> -->
      </div>
      <!-- <div class="countdown" v-if="drillDetail.progress != 4">
        <template v-if="drillDetail.progress != 5">
          <span v-if="drillStatus == 1">开始</span
          ><span v-if="drillStatus != 1">结束</span>倒计时：<b>
            <span>{{ time.h }}</span
            >:<span>{{ time.m }}</span
            >:<span>{{ time.s }}</span></b
          >
        </template>
        <strong v-else>
          暂停中
        </strong>
      </div> -->
      <div class="btn-group">
        <div class="flex">
          <!-- <Poptip
            confirm
            title="为确保可视化展示效果，建议使用chrome浏览器查看大屏。"
            @on-ok="showVisualizationQuestion('Question')"
            transfer
            word-wrap
            width="250"
          >
            <Button type="primary">
              <img src="../../assets/scene/dis-screen.png" />可视化题目统计
            </Button>
          </Poptip> -->
          <!-- <Button type="primary" @click="handleGoCircumstances">进入环境</Button> -->
        </div>
      </div>
    </div>
    <!-- {{contentDetail}} -->
    <p v-if="gitInfo.userName && contentDetail.deployStatus === 3 && (contentDetail.envStatus == 1 || contentDetail.envStatus == 3)" class="git-wrap">
        <span>代码库访问地址：<a :href="gitInfo.gitServerUrl" target="_blank">{{ gitInfo.gitServerUrl }}</a></span></a>
        <Divider type="vertical"></Divider>
        <span>用户名：{{ gitInfo.userName }}</span>
        <Divider type="vertical"></Divider>
        <span>密码：{{ gitInfo.password }}</span>
    </p>
    <Tabs
      class="demo-tabs-style2"
      @on-click="changeTab"
      :value="curTab"
    >
        <template v-for="(tab,index) in tabList">
            <TabPane :name="tab.name" :label="tab.label" :key="tab.name" :index="tab.index" v-if="tab.show">
                <component 
                    v-if="curTab === tab.name" 
                    :is="curTab" 
                    :contentId="contentDetail.id"
                    :projectId="contentDetail.projectId"
                    :sceneId="contentDetail.sceneId"
                    :prjId="contentDetail.projectId"
                    :disabledAllBtn="disabledAllBtn">
                </component>
            </TabPane>
        </template>
    </Tabs>
  </div>
</template>

<script>
import EnvironDesign from './component/environDesign.vue';
// import DeviceManage from './environManage';
import DeviceManage from  './environ/environManage.vue'
import User from './component/accessUserToGroup.vue'
import Refs from './component/refs.vue'
import TaskAssign from './component/taskAssign.vue'
import MyTask from './component/myTask.vue'
import Summary from './summary'
import Statistics from './component/statistics.vue'
import Jupyter from '../jupyter';
import Task from './task'
import { mapState, mapMutations } from 'vuex';
import timer from '@/mixin/timer';
import { getContentDetail, updateContent } from '../api/content.js';
import { getReportList } from '../api/report.js';
import { getGitInfo } from '../api/gitManage.js';
import { selectStatus } from '../api/environment.js';
import {
    deployProject,
    queryProjectstatus,
    getDeployProgress,
    clearDeloyPro,
    getTestList,
    queryNetworkList,
} from '../api/deploy.js';
export default {
  name: 'Detail',
  components: {
    EnvironDesign,
    User,
    Refs,
    TaskAssign,
    MyTask,
    Summary,
    Jupyter,
    Task,
    DeviceManage,
    Statistics
  },
  mixins: [timer],
  data() {
    return {
      id:this.$route.query.id,
      step:0,
      preDefault:'EnvironManage',
      imageModal: false,
      contentDetail: { id: this.$route.query.id, name: '', tmplId: '', statusCHName: '未部署' },
      designModal: {
          show: false,
          title: '环境设计',
      },
      fullShow: {
          topo: false,
          process: false,
          code: false,
      },
      load: {
          topo: false,
          process: false,
      },
      topoIframeHeight: '400px',
      screenImgSrc: require('../assets/research/screen.png'),
      screenHoverImgSrc: require('../assets/research/screenOut.png'),
      showDeployTip: false,
      curTab: '',
      gitInfo: {},
      linkCheckModal:{
          show:false
      },
      protocolModal:{
          show:false
      },
      vmcmdModal:{
          show:false
      }
    };
  },
  filters: {},
  provide() {
    return {
      detailParent:this
    };
  },
  beforeDestroy() {
    
  },
  beforeRouteLeave(to, from, next) {
    if (to.path === '/researchDesign') {
      next();
    } else {
      //跳转至非攻防赛页面，清空存储的查询条件
      sessionStorage.removeItem('queryObj');
      next();
    }
  },
  computed: {
      ...mapState('user', {
          'USER_ID':state => state.userId,
          'isRootDesigner':state => state.isRootDesigner
      }),
      disabledAllBtn(){
        return this.contentDetail.creator !== this.USER_ID
      },
      tabList(){
        return [
          {
            label:"环境管理",
            name:'EnvironDesign',
            show:this.step === 0 && this.isRootDesigner && this.contentDetail.id,
            index:1
          },
          {
            label:"人员组织",
            name:'User',
            show:this.step === 0 && this.isRootDesigner && this.contentDetail.id,
            index:2
          },
          {
            label:"任务分配",
            name:'TaskAssign',
            show:[0,1].includes(this.step) && this.isRootDesigner && this.contentDetail.id && this.contentDetail.prjId,
            index:3
          },
          {
            label:"我的任务",
            name:'MyTask',
            show:[0,1].includes(this.step) && !this.isRootDesigner && this.contentDetail.id && this.contentDetail.prjId,
            index:4
          },
          {
            label:"参考资料",
            name:'Refs',
            show:[0,1].includes(this.step) && this.contentDetail.id,
            index:5
          },
          {
            label:'设备管理',
            name:'DeviceManage',
            show:[0].includes(this.step) && this.isRootDesigner && this.contentDetail.id,
            index:6
          },
          {
            label:"编程环境",
            name:'Jupyter',
            index:7,
            show:
                this.contentDetail.projectId && 
                this.contentDetail.deployStatus === 3 &&
                [1, 2, 3].includes(this.envStatus) && this.step !== 2
          },
          {
            label:"环境事务",
            name:'Task',
            show:this.step === 0 && this.contentDetail.id,
            index:8
          },
          {
            label:"科研文档",
            name:'Summary',
            show:this.step === 2 && this.contentDetail.id,
            index:9
          },
          {
            label:"统计",
            name:'Statistics',
            show:this.step === 2 && this.isRootDesigner && this.contentDetail.id,
            index:10
          },
        ]
      },
      showTabList(){
        return this.tabList.filter(tab => tab.show)
      },
      deployStatus() {
          return this.contentDetail.deployStatus;
      },
      envStatus() {
          return this.contentDetail.envStatus;
      },
      generateImageList() {
          return this.contentDetail.generateImageList || [];
      }
    },
    watch: {
        tabList(val){
           let showTabs = val.filter(tab => tab.show).map(tab => tab.name);
           if(!showTabs.includes(this.curTab) || !this.curTab){
            this.curTab = showTabs[0]
           }
        },
        deployStatus(val, oldVal) {
            if (val === 3) {
                this.getContentDetail('poll');
            }
        }
    },
    async mounted() {
        let _this = this;
        this.curTab = this.isRootDesigner ? 'EnvironDesign' : 'MyTask';
        // window.cancelFullScreen = () => {
        //     console.log('取消全屏');
        //     if (!_this.fullShow['topo']) {
        //         return;
        //     }
        //     _this.fullShow['topo'] = false;
        //     // document.getElementById('topoIframe').contentWindow.changeShowType('view');
        // };
        document.addEventListener('visibilitychange', this.handleVisible);
        if (!this.$route.query.id) {
            return;
        }
        this.getGitInfo();
        await this.getContentDetail();
        this.addBreadItem({
            name: this.contentDetail.name,
        });
    },
    beforeDestroy() {
        clearTimeout(this.progressTimeout);
        clearTimeout(this.statusTimeout);
        clearTimeout(this.sceneTimeout);
        clearInterval(this.detailTimeout);
        document.removeEventListener('visibilitychange', this.handleVisible);
    },
    methods: {
        ...mapMutations(['addBreadItem']),
        changeStep(step){
            this.curTab = '';
            setTimeout(() => {
                this.step = step;
            })
        },
        changeTab(value) {
            this.curTab = value;
        },
        handleVisible() {
            if (document.visibilityState === 'visible') {
                if (this.contentDetail && this.contentDetail.projectId) {
                    this.$refs['imageList'] && this.$refs['imageList'].getCreateImageList();
                    // this.load = {
                    //     topo: false,
                    //     process: false
                    // };
                    // document.getElementById('topoIframe') &&
                    //     document.getElementById('topoIframe').contentWindow.location.reload(true);
                    // document.getElementById('processIframe') &&
                    //     document
                    //         .getElementById('processIframe')
                    //         .contentWindow.location.reload(true);
                    this.getContentDetail();
                }
            } else {
            }
        },
        getImageList() {
            this.$refs['imageList'] && this.$refs['imageList'].getCreateImageList();
        },
        getContentDetail(type) {
            if (!this.$route.query.id) {
                return;
            }
            return new Promise((resolve, reject) => {
                getContentDetail(this.$route.query.id).then(({ code, data: detail }) => {
                    if (code === 1) {
                        if (this.contentDetail.id) {
                            this.contentDetail = { ...this.contentDetail, ...detail };
                        } else {
                            this.contentDetail = detail;
                        }
                        this.contentDetail.prjId = this.contentDetail.projectId;
                        if (!this.contentDetail.projectId) {
                            this.contentDetail.imageList = [];
                        }
                        // this.getRepTemplateList();
                        if (type !== 'poll') {
                            if(this.isRootDesigner){
                                this.queryProjectstatus();
                            }else{
                                this.getTestList(this.contentDetail.prjId); //获取场景列表
                            }
                        } else {
                            if ([0, 2].includes(this.contentDetail.envStatus)) {
                                this.detailTimeout = setTimeout(() => {
                                    this.getContentDetail('poll');
                                }, 5000);
                            } else {
                                clearTimeout(this.detailTimeout);
                            }
                        }
                        // this.getExperStatus();
                        // this.getReportList();
                        resolve();
                    }
                });
            });
        },
        getTestList(projectId) {
            clearTimeout(this.sceneTimeout);
            getTestList(projectId).then(({ code, data, message }) => {
                if (code === 1) {
                    if (data.items.length > 0) {
                        this.contentDetail.sceneId = data.items[0].id;
                    } else {
                        this.sceneTimeout = setTimeout(() => {
                            this.getTestList(projectId);
                        }, 3000);
                    }
                }
            });
        },
        getNetworkList(projectId, networkId) {
            queryNetworkList(projectId, networkId).then(({ code, attribute = {} }) => {
                if (code === 1 && attribute.editorStage && attribute.editorStage.deviceNum) {
                    this.updateDetail({
                        hasNode: true,
                    });
                }
            });
        },
        getExperStatus() {
            return new Promise((resolve) => {
                selectStatus(this.contentDetail.id)
                    .then(({ code, data, message }) => {
                        let { projectId, deployStatus } = data;
                        this.updateDetail({ deployStatus, prjId: projectId });
                        resolve();
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            });
        },
        getReportList() {
            let params = {
                contentId: this.contentDetail.id,
                pageIndex: 1,
                pageSize: 1,
            };
            getReportList(params).then((res) => {
                if (res.code == 1) {
                    this.updateDetail({ summaryTotal: res.data.total });
                }
            });
        },
        updateDetail(data) {
            this.contentDetail = { ...this.contentDetail, ...data };
        },
        updateTemplate(data) {
            this.updateContent({ tmplId: data.id, tmplName: data.name });
        },
        updateContent(data) {
            updateContent(this.contentDetail.id, data)
                .then(({ code, message }) => {
                    if (code === 1) {
                        this.$Message.info('保存成功');
                    } else {
                        this.$Message.error(message);
                    }
                })
                .catch((error) => {});
        },
        // 更新模板信息，创建工程
        createProject() {},
        async deploy() {
            await this.deployProject(this.contentDetail.projectId);
            this.queryProjectstatus();
        },
        deployProject() {
            return new Promise((resolve, reject) => {
                deployProject(this.contentDetail.projectId).then(({ code, data, message }) => {
                    if (code === 1 || code === 3) {
                        resolve(code);
                    } else {
                        this.$Message.warning(message);
                    }
                });
            });
        },
        queryProjectstatus() {
            clearTimeout(this.statusTimeout);
            this.showDeployTip = false;
            if (!this.contentDetail.projectId) {
                return;
            }
            return new Promise((resolve, reject) => {
                queryProjectstatus(this.contentDetail.projectId).then(
                    ({ code, data, message }) => {
                        if (code === 1) {
                            let { project, network } = data;
                            let {
                                id,
                                deployId,
                                status,
                                statusCHName,
                                checkOuts = [],
                                errorMessage,
                            } = project;
                            this.getTestList(id); //获取场景列表
                            // this.getNetworkList(id, network.id); //获取子网络列表
                            this.updateDetail({
                                deployStatus: status,
                                statusCHName: statusCHName,
                                networkId: network.id,
                                errorMessage:errorMessage
                            });
                            if (checkOuts.length != 0) {
                                let errorContent = '';
                                checkOuts.forEach((item,i) => {
                                    item.data.forEach((dataItem,dataIndex) => {
                                        dataItem.deviceName = dataItem.deviceName
                                            ? dataItem.deviceName
                                            : dataItem.networkName;
                                        errorContent +=
                                            dataItem.deviceName +
                                            '中的' +
                                            dataItem.name +
                                            item.message +
                                            '<br/>';
                                    });
                                });
                                // this.$Message.error({
                                //     content: errorContent,
                                //     closable: true,
                                //     duration: 60
                                // });
                                this.showDeployTip = true;
                            } else if (errorMessage) {
                                this.showDeployTip = true;
                                // this.$Message.error({
                                //     content: errorMessage,
                                //     closable: true,
                                //     duration: 30
                                // });
                            } else {
                                if (status === 9 || status === 13) {
                                    //部署中 || 清空部署中
                                    this.getDeployProgress(deployId);
                                } else if (status === 15 || status === 16) {
                                    //校验中
                                    this.statusTimeout = setTimeout(() => {
                                        this.queryProjectstatus();
                                    }, 5000);
                                } else if (status === 3) {
                                }
                            }
                            resolve(project);
                        } else {
                            this.updateDetail({ projectId: '' });
                            code != -2 && this.$Message.warning(message);
                        }
                    }
                );
            });
        },
        getDeployProgress(deployId) {
            clearTimeout(this.progressTimeout);
            return new Promise((resolve, reject) => {
                getDeployProgress(deployId).then(({ code, data, message }) => {
                    let { deployStatus, process } = data;
                    if (code === 1) {
                        this.updateDetail({ process });
                        if (deployStatus === 1) {
                            // 还在部署中，持续获取部署进度
                            if (process != 100) {
                                this.progressTimeout = setTimeout(() => {
                                    this.getDeployProgress(deployId);
                                }, 5000);
                            }
                        } else {
                            // 部署完成
                            this.queryProjectstatus();
                        }
                        resolve(data);
                    } else {
                        this.$Message.warning(message);
                    }
                });
            });
        },
        clearDeploy() {
            // this.loading = true;
            // this.distriTip = '正在清空工程';
            let params = {
                projectId: this.contentDetail.projectId,
            };
            clearDeloyPro(this.contentDetail.projectId, params)
                .then((res) => {
                    if (res.code === 1 || res.code === 3) {
                        this.queryProjectstatus();
                    } else {
                        // this.loading = false;
                        this.$Message.error({
                            content: res.message,
                            duration: 3,
                        });
                    }
                })
                .catch((err) => {
                    console.log(err);
                    // this.loading = false;
                    this.$Message.error('服务器连接失败！');
                });
        },
        refreshDocInfo() {
            this.$refs.docInfo1.getResourceBind();
            this.$refs.docInfo2.getResourceBind();
        },
        gotoTopo() {
            window.openTrain(
                `http://localhost:8081/#/topologyDisplay/topologys?projectId=${this.contentDetail.projectId}&ecId=${this.contentDetail.id}&ecName=${this.contentDetail.name}`
            );
            // window.openTrain(
            //     `/ky-topologyProject/index.html#/topologyDisplay/topologys?projectId=${this.contentDetail.projectId}&ecId=${this.contentDetail.id}&ecName=${this.contentDetail.name}`
            // );
        },
        gotoEdit() {
            window.openTrain(
                `/14-NetTopology/TopoEdit.html?project=${this.contentDetail.projectId}&networkid=${this.contentDetail.networkId}&hideReturnBtn=true`
            );
            // window.openTrain(
            //     `http://172.172.100.1/14-NetTopology/TopoEdit.html?project=${this.contentDetail.projectId}&networkid=${this.contentDetail.networkId}&fromProject=ky-topologyProject`
            // );
        },
        gotoProcess() {
            // window.openTrain(
            //     `http://172.172.100.1/ky-topologyProject/index.html#/topologyDisplay/processPanel/processControl?projectId=${this.contentDetail.projectId}&sceneId=${this.contentDetail.sceneId}`
            // );
            window.openTrain(
                `/ky-topologyProject/index.html#/topologyDisplay/processPanel/processControl?projectId=${this.contentDetail.projectId}&sceneId=${this.contentDetail.sceneId}`
            );
        },
        refreshTopo() {
            if (!this.load.topo) {
                return;
            }
            this.load.topo = false;
            this.$refs['vm-statistics'].document.getElementById('topoIframe') &&
                document.getElementById('topoIframe').contentWindow.location.reload(true);
        },
        refreshProcess() {
            if (!this.load.process) {
                return;
            }
            this.load.process = false;
            document.getElementById('processIframe') &&
                document.getElementById('processIframe').contentWindow.location.reload(true);
        },
        fullScreen(type) {
            if (type === 'topo') {
                // 调用iframe中的方法
                document.getElementById('topoIframe').contentWindow.changeShowType(this.fullShow[type] ? 'view' : 'edit');
            } else {
                
            }
            this.fullShow[type] = !this.fullShow[type];
        },
        loadSuccess(type) {
            this.load[type] = true;
            if (type === 'code') {
                //不同源无法js交互
                // document.getElementById('codeIframe').contentWindow.document.getElementById('header').style.display = 'none';
            }
        },
        getGitInfo() {
            getGitInfo().then(({ code, data, message }) => {
                if (code == 1) {
                    this.gitInfo = data;
                }
            });
        },
        openLinkCheckModal(){
            this.linkCheckModal.show = true;
        },
        openProtocolModal(){
            this.protocolModal.show = true;
        },
        openCmdModal(){
            this.vmcmdModal.show = true;
        },
    }
};
</script>
<style scoped src="@/view/drill_compete/detail.css">
</style>
<style scoped>
    .demo-tabs-style2 /deep/ .ivu-tabs-content {
        height:calc(100% - 80px)
    }
    .demo-tabs-style2 /deep/ .ivu-tabs-content .ivu-tabs-tabpane{
        padding: 20px!important;
    }
    /* .sceneDetail .demo-tabs-style2{
        height: 0;
    } */
    .step-group .vu-steps /deep/ .ivu-steps-head-inner {
        cursor: pointer;
    }
    .git-wrap {
        padding: 14px 10px;
        margin-bottom: 10px;
        background: var(--card-body-bgcolor) !important;
    }
</style>
